package com.example.weather

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemClickListener
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.ListView
import android.widget.Spinner
import androidx.appcompat.app.AppCompatActivity
import com.example.weather.More.ContactAdapter
import com.example.weather.data.City
import com.example.weather.data.CityDao
import com.example.weather.data.Person
import com.example.weather.data.WeatherDatabase
import com.google.gson.Gson
import org.xutils.common.Callback
import org.xutils.common.Callback.CommonCallback
import org.xutils.http.RequestParams
import org.xutils.x
import java.text.ParseException
import java.util.ArrayList

/**
 * @author Y7993
 * MsgActivity类用于展示消息功能，包括获取联系人信息和天气信息等
 */
class MsgActivity : AppCompatActivity() {
    private var arr_adapter: ArrayAdapter<String?>? = null
    var et: EditText? = null
    var phone_num: EditText? = null
    var msg_messge: EditText? = null
    private val personList: MutableList<Person> = ArrayList<Person>()
    var lv_phonelist: ListView? = null
    private var cityDao: CityDao? = null
    var hotCitys: Array<String?> = arrayOf<String?>(
        "北京",
        "太原",
        "沈阳",
        "重庆",
        "天津",
        "南宁",
        "杭州",
        "武汉",
        "烟台",
        "西安"
    )
    var url1: String =
        "https://wis.qq.com/weather/common?source=pc&weather_type=observe|index|rise|alarm|air|tips|forecast_24h&province="
    var url2: String = "&city="
    var message: String? = null

    @SuppressLint("CutPasteId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_msg)
        et = findViewById<EditText>(R.id.msg_messge_city)
        phone_num = findViewById<EditText>(R.id.msg_phone)
        lv_phonelist = findViewById<ListView>(R.id.lv_phone)
        val weatherDatabase = WeatherDatabase.getDatabase(this)
        cityDao = weatherDatabase.getCityDao()
        msg_messge = findViewById<EditText>(R.id.msg_messge_city)
        initview()
    }

    /**
     * 添加电话号码，获取联系人信息
     */
    fun addPhoneNumber() { //内容提供者
        val uri_raw_contact = Uri.parse("content://com.android.contacts/raw_contacts")
        val uri_data = Uri.parse("content://com.android.contacts/data")
        val resolver = contentResolver
        val cursor =
            resolver.query(uri_raw_contact, arrayOf<String>("contact_id"), null, null, null)
        if (cursor != null) {
            while (cursor.moveToNext()) {
                val id = cursor.getString(0)
                /**获取联系人id */
                println("$id*****")
                val cursor1 = resolver.query(
                    uri_data,
                    arrayOf<String>("mimetype", "data1"),
                    "raw_contact_id=?",
                    arrayOf<String?>(id),
                    null
                )
                if (cursor1 == null) {
                    continue
                }
                val person = Person()
                while (cursor1.moveToNext()) {
                    val mimetype_id = cursor1.getString(0)
                    var data1 = cursor1.getString(1)
                    if ("vnd.android.cursor.item/name" == mimetype_id) {
                        person.name = data1
                    }
                    if ("vnd.android.cursor.item/phone_v2" == mimetype_id || "vnd.android.cursor.item/vnd.com.tencent.mobile.qq.voicecall.profile" == mimetype_id) {
                        data1 = data1.replace(" ", "")
                        person.number = data1
                    }
                }
                if (person.number == null) {
                    continue
                }
                personList.add(person)
                cursor1.close()
            }
        }
        cursor?.close()
        if (!personList.isEmpty()) {
            for (t in personList) {
                println(t)
            }
        }

        lv_phonelist!!.visibility = View.VISIBLE
        lv_phonelist!!.adapter = ContactAdapter(this, personList.map { it as Person? }.toMutableList())
        lv_phonelist!!.onItemClickListener =
            OnItemClickListener { adapterView: AdapterView<*>?, view1: View?, i: Int, l: Long ->
                val person = personList[i]
                val number = person.number
                phone_num!!.setText(number)
                lv_phonelist!!.visibility = View.GONE
            }
    }

    /**
     * 初始化视图，包括城市选择器和适配器设置
     */
    fun initview() {
        val spinner = findViewById<Spinner>(R.id.spinner_test)
        //将data_list的数据变为数据库中的
        //数据
        var data_list = getData()
        //适配器
        arr_adapter = ArrayAdapter<String?>(this, android.R.layout.simple_spinner_item, data_list)
        //设置样式
        arr_adapter!!.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        //加载适配器
        spinner.adapter = arr_adapter
        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                adapterView: AdapterView<*>?,
                view: View?,
                i: Int,
                l: Long
            ) {
                val now_city = arr_adapter!!.getItem(i)
                message = "$now_city,"
                val now_provice = GetProvice(now_city!!)
                val url = url1 + now_provice + url2 + now_city
                val rp = RequestParams(url)
                x.http().get<String?>(rp, MyCallBackk())
            }

            override fun onNothingSelected(adapterView: AdapterView<*>?) {
            }
        }
    }

    /**
     * 获取城市数据，如果城市数据库为空则插入热门城市
     * @return 城市名称列表
     */
    private fun getData(): MutableList<String?> {
        val cityList: MutableList<String?> = ArrayList<String?>()
        var cities = cityDao!!.findAll()
        cities?.let {
            if (it.isEmpty()) {
                for (tmp_name in hotCitys) {
                    cityDao!!.insetCity(City(tmp_name))
                    println("插入了城市$tmp_name\n")
                }
                cities = cityDao!!.findAll()
            }
        }
        if (cities != null) {
            for (c in cities) {
                c?.let { cityList.add(it.getName()) }
                println(c)
            }
        }
        return cityList
    }
    /**
     * 发送信息，跳转到MsgModelActivity
     */
    fun msg_on() {
        val intent = Intent(this, MsgModelActivity::class.java)
        intent.putExtra("msg", et!!.text.toString().trim { it <= ' ' })
        startActivityForResult(intent, 0)
    }

    /**
     * 返回以跳转到MoreActivity
     */
    fun msg_back() {
        val intent = Intent(this, MoreActivity::class.java)
        startActivityForResult(intent, 0)
    }

    override fun onActivityResult(requestCode: Int, resultCoder: Int, data: Intent?) {
        if (resultCoder == 1) {
            val message = data!!.getStringExtra("msg")
            et!!.setText(message)
        }
        super.onActivityResult(requestCode, resultCoder, data)
    }

    /**
     * 发送短信功能
     */
    fun sendMsg() {
        val sms = Uri.parse("smsto:" + phone_num!!.text.toString().trim { it <= ' ' })
        val intent = Intent()
        intent.action = Intent.ACTION_SENDTO
        intent.data = sms
        intent.putExtra("sms_body", et!!.text.toString().trim { it <= ' ' })
        startActivity(intent)
    }

    /**
     * 自定义回调类，用于处理异步请求的结果
     */
    inner class MyCallBackk : CommonCallback<String?> {
        override fun onSuccess(result: String?) {
            //        解析并展示数据
            try {
                parseShowData(result)
            } catch (e: ParseException) {
                e.printStackTrace()
            }
            println(result)
            println("SUCCESS")
        }

        override fun onError(ex: Throwable?, isOnCallback: Boolean) {
            println("***$ex")
            println("ERROR")
        }

        override fun onCancelled(cex: Callback.CancelledException?) {
        }

        override fun onFinished() {
            println("完成")
        }
    }

    /**
     * 解析并显示天气数据
     * @param result 返回的天气数据
     * @throws ParseException 解析失败异常
     */
    @Throws(ParseException::class)
    private fun parseShowData(result: String?) {
//        使用gson解析数据
        val weatherBean = Gson().fromJson<WeatherBean>(result, WeatherBean::class.java)
        val resultsBean = weatherBean.data
        println(result)
        //        获取今日天气情况
        val todayDataBean = resultsBean.observe
        message = message + "天气：" + todayDataBean.weather_short + ","
        message = message + "风向 " + "西南风" + todayDataBean.wind_power + "级,"
        message = message + "当前温度：" + todayDataBean.degree + "°C"
        msg_messge!!.setText(message)
        println("$message*****")
    }


    /**
     * 根据城市名称获取省份
     * @param city 城市名称
     * @return 省份名称
     */
    private fun GetProvice(city: String): String? {
        val Citys = arrayOf<String?>(
            "北京",
            "上海",
            "广东省 广州",
            "广东省 深圳",
            "广东省 珠海",
            "广东省 佛山",
            "江苏省 南京",
            "江苏省 苏州",
            "福建省 厦门",
            "湖南省 长沙",
            "四川省 成都",
            "福建省 福州",
            "浙江省 杭州",
            "湖北省 武汉",
            "山东省 烟台",
            "陕西省 西安",
            "山西省 太原",
            "辽宁省 沈阳",
            "重庆",
            "天津",
            "广西省 南宁"
        )
        var provice: String? = null
        for (s in Citys) {
            if (s!!.contains(city)) {
                provice = s.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0]
                break
            }
        }
        return provice
    }
}
